package study.netty.websocket.support.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketServer {

    private EventLoopGroup bossGroup;

    private EventLoopGroup workGroup;

    private ServerBootstrap bootstrap;

    private ChannelFuture channelFuture;

    public WebSocketServer() {

    }

    public void bind() {
        try {
            bossGroup = new NioEventLoopGroup();
            workGroup = new NioEventLoopGroup();
            bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new WebSocketChannelInitializer());

            channelFuture = bootstrap.bind(8899)
                    .sync();

            //进行阻塞，等待服务器连接关闭之后 main 方法退出，程序结束
            channelFuture.channel()
                    .closeFuture()
                    .sync();
        } catch (Exception ex) {
            log.error("", ex);
            System.exit(9);
        }
    }

    public void shutdown() {
        log.info("shutdown");
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }

    public void start() {
        log.info("start");
        bind();
    }
}
